package com.djmw.mouse.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.djmw.mouse.entity.Industry;
import com.djmw.mouse.entity.IndustryNode;
import com.djmw.mouse.repository.IndustryDao;

//Spring Bean的标识.
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional(readOnly = true)
public class IndustryService {

	private IndustryDao industryDao;

	private List<IndustryNode> allIndustriesTree;

	public Industry getIndustry(Long id) {
		return industryDao.findOne(id);
	}

	@Transactional(readOnly = false)
	public Industry saveIndustry(Industry entity) {
		return industryDao.save(entity);
	}

	@Transactional(readOnly = false)
	public void deleteIndustry(Long id) {
		Industry industry = industryDao.findOne(id);
		if (industry != null) {
			if (industry.getParent() == null) {
				// Level 1 industry
				industryDao.deleteLevelOneIndustry(id);
			} else {
				// Level 2 industry
				industryDao.delete(id);
			}
		}
	}

	@Transactional(readOnly = false)
	public void deleteLevelOneIndustry(Long id) {
		industryDao.deleteLevelOneIndustry(id);
	}

	@Transactional(readOnly = false)
	public List<Industry> getAllIndustries() {
		return (List<Industry>) industryDao.findAll();
	}

	public List<IndustryNode> getAllIndustriesTree() {
		if (allIndustriesTree == null) {
			List<Industry> allIndustries = getAllIndustries();
			allIndustriesTree = new ArrayList<IndustryNode>();
			HashMap<Industry, IndustryNode> map = new HashMap<Industry, IndustryNode>();
			for (Industry industry : allIndustries) {
				IndustryNode node = new IndustryNode(industry);
				Industry parent = industry.getParent();
				if (parent == null) {
					map.put(industry, node);
					allIndustriesTree.add(node);
				} else {
					map.get(parent).addSubIndustry(node);
				}
			}
		}
		return allIndustriesTree;
	}

	@Autowired
	public void setIndustryDao(IndustryDao industryDao) {
		this.industryDao = industryDao;
	}
}
